import pymysql

connection = pymysql.connect(host='127.0.0.1',
                             user='root',
                             password='ys_nj_sst!',
                             database='new_ys_wms',
                             cursorclass=pymysql.cursors.DictCursor)


# 增删改
def execute_none_query(cursor, connect, sql, param=None):
    if param is None:
        cursor.execute(sql)
    else:
        cursor.execute(sql, param)
    connect.commit()


# 查询
def execute_query(cursor, sql, param=None):
    if param is None:
        cursor.execute(sql)
    else:
        cursor.execute(sql, param)
    return cursor.fetchall()


if __name__ == "__main__":
    # 获取连接
    connect = connection
    # 获取游标
    cursor = connect.cursor()

    # 查询数据
    ret1 = execute_query(
        cursor=cursor,
        sql='select * from `t_unint` where `unit` = %s',
        param=('米',)
    )
    ret2 = execute_query(
        cursor=cursor,
        sql='select * from `t_unint` where `unit` = \'个\''
    )
    print(ret1)
    print(ret2)

    # 增加数据
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql='insert into t_unint(unit, create_time) values (%s, %s)',
        param=('测试', '2025-04-23 17:04:52')
    )
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql=f'insert into t_unint(unit, create_time) values (\'测试1\', \'2025-04-23 17:04:52\')'
    )

    # 修改数据
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql='update t_unint set unit = %s where unit = %s',
        param=('测试2', '测试')
    )
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql='update t_unint set unit = \'测试3\' where unit = \'测试1\''
    )

    # # 删除数据
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql='delete from t_unint where unit = %s',
        param=('测试2',)
    )
    execute_none_query(
        connect=connect,
        cursor=cursor,
        sql='delete from t_unint where unit = \'测试3\'',
    )
